﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace Bowlus.Common
{
    public class AppHostInstance : IComparable
    {
        // Instance name, ie. Bowluw.AppHost_IN_0
        public string Name { get; set; }

        // Instance internal IP, ie. 127.255.0.0
        public string IP { get; set; }

        public int CompareTo(object obj)
        {
            if (obj != null && obj is AppHostInstance)
            {
                AppHostInstance ah = obj as AppHostInstance;
                return Name.CompareTo(ah.Name);
            }
            return -1;
        }

        public static IList<AppHostInstance> GetAppHosts()
        {
            var webfarmRole = RoleEnvironment.Roles[BowlusSettings.AppHostRoleName];

            var appHosts = new List<AppHostInstance>();
            foreach (var appHost in webfarmRole.Instances)
            {
                var ip = appHost.InstanceEndpoints[BowlusSettings.AppHostEndpointName].IPEndpoint.Address.ToString();
                appHosts.Add(new AppHostInstance(){
                    Name = appHost.Id,
                    IP = ip
                });
            }
            return appHosts;
        }
    }
}
